package com.example.studentknowledge.repository;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Favorite;
import com.example.studentknowledge.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * 收藏Repository接口
 */
@Repository
public interface FavoriteRepository extends JpaRepository<Favorite, Long> {
    
    /**
     * 根据用户查找收藏
     */
    Page<Favorite> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
    
    /**
     * 根据文章查找收藏
     */
    Page<Favorite> findByArticleOrderByCreatedAtDesc(Article article, Pageable pageable);
    
    /**
     * 查找用户对特定文章的收藏
     */
    Optional<Favorite> findByUserAndArticle(User user, Article article);
    
    /**
     * 检查用户是否收藏了文章
     */
    boolean existsByUserAndArticle(User user, Article article);
    
    /**
     * 统计用户的收藏数
     */
    @Query("SELECT COUNT(f) FROM Favorite f WHERE f.user = :user")
    Long countByUser(@Param("user") User user);
    
    /**
     * 统计文章的收藏数
     */
    @Query("SELECT COUNT(f) FROM Favorite f WHERE f.article = :article")
    Long countByArticle(@Param("article") Article article);
    
    /**
     * 删除用户的所有收藏
     */
    void deleteByUser(User user);
    
    /**
     * 删除文章的所有收藏
     */
    void deleteByArticle(Article article);
    
    /**
     * 删除用户对文章的收藏
     */
    void deleteByUserAndArticle(User user, Article article);
}